package com.station.service.impl;

import com.google.gson.Gson;
import com.kingdee.bos.webapi.entity.RepoResult;
import com.station.entity.KingErpBillRecord;
import com.station.enums.ErpOrderTypeEnum;
import com.station.param.request.otherout.*;
import com.station.service.KingErpBillRecordService;
import com.station.service.OtherOutService;
import com.station.service.mapper.ItemMapper;
import com.station.service.mapper.SaleOrderMapper;
import com.station.service.mapper.UnitMapper;
import com.station.utils.DateUtils;
import com.station.utils.KingDeeUtils;
import com.station.utils.R;
import com.station.utils.StringUtils;
import com.station.vo.ItemVo;
import com.station.vo.UnitVo;
import com.station.vo.UseDetail;
import com.station.vo.UseOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: dongfangyu
 * @Date: 2025/11/12
 */
@Service
public class OtherOutServiceImpl implements OtherOutService {

    @Autowired
    private SaleOrderMapper saleOrderMapper;
    @Autowired
    private UnitMapper unitMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private KingErpBillRecordService kingErpBillRecordService;

    @Value("${rd.bld.vendorId}")
    private String vendorId;

    /**
     * 其他入库单批量保存标识
     */
    private static final String FormId_OtherOrder = "STK_MisDelivery";
    /**
     * 分组前缀
     */
    private static final String F_GROUP_PREFIX = "03.13";
    private static final String lyOrderType = "002";
    private static final String xcOrderType = "001";
    /**
     * 仓库前缀
     */
    private static final String STORE_PREFIX = "bld";

    private static final String ORG_ID = "100";

    private static final String OWNER_TYPE_ID = "BD_OwnerOrg";

    @Override
    public R syncUsedOrderList(String startDate, String endDate) {
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            String[] perDate = DateUtils.getPerDate();
            startDate = perDate[0];
            endDate = perDate[1];
        }
        List<UseOrder> useOrders = saleOrderMapper.queryUseOrderList(Long.valueOf(vendorId),startDate, endDate);
        List<KingErpBillRecord> records = new ArrayList<>();
        if (!CollectionUtils.isEmpty(useOrders)) {
            Model[] models = new Model[useOrders.size()];
            int index = 0;
            for (UseOrder useOrder : useOrders) {
                List<UseDetail> useDetails = saleOrderMapper.queryUseOrderDetailList(useOrder.getOrderNo());
                OtherOutFEntity[] fEntities = new OtherOutFEntity[useDetails.size()];
                int detailIndex = 0;
                if(!CollectionUtils.isEmpty(useDetails)){
                    for (UseDetail useDetail : useDetails) {
                        //拼接明细数据
                        UnitVo unitVo = unitMapper.queryUnitByCondition(Long.valueOf(vendorId), useDetail.getStockUnit());
                        String unitCode = "Pcs";
                        if (null != unitVo && null != unitVo.getUnitCode()) {
                            unitCode = unitVo.getUnitCode();
                        }
                        OtherOutFEntity otherOutFEntity = new OtherOutFEntity();
                        ItemVo itemVo = itemMapper.queryItemBySkuCode(Long.valueOf(vendorId), useDetail.getSkuCode());
                        String cartId = null;
                        if (StringUtils.isEmpty(itemVo.getParentCode())) {
                            cartId = itemVo.getCatCode();
                        } else {
                            cartId = itemVo.getParentCode() + "." + itemVo.getCatCode();
                        }
                        otherOutFEntity.setFMaterialId(new FMaterialId(F_GROUP_PREFIX + "." + cartId + "." + itemVo.getItemId()));
                        otherOutFEntity.setFUnitID(new FUnitID(unitCode));
                        otherOutFEntity.setFBaseUnitId(new FBaseUnitId(unitCode));
                        otherOutFEntity.setFQty(useDetail.getUseQuantity());
                        otherOutFEntity.setFStockId(new FStockId(STORE_PREFIX + useOrder.getStoreCode()));
                        otherOutFEntity.setFOwnerTypeId(OWNER_TYPE_ID);
                        otherOutFEntity.setFOwnerId(new FOwnerId(ORG_ID));
                        otherOutFEntity.setFStockStatusId(new FStockStatusId("KCZT01_SYS"));
                        otherOutFEntity.setFKeeperTypeId("BD_KeeperOrg");
                        otherOutFEntity.setFKeeperId(new FKeeperId(ORG_ID));
                        fEntities[detailIndex++] = otherOutFEntity;
                    }
                } else {
                    return R.ok("未查询到单据明细数据！");
                }
                //拼接订单数据
                Model model = new Model();
                model.setFBillNo(useOrder.getOrderNo());
                model.setFBillTypeID(new FBillTypeID(useOrder.getPurpose() == 0 ? xcOrderType:lyOrderType));
                model.setFDate(useOrder.getBizDate());
                model.setFStockOrgId(new FStockOrgId(ORG_ID));
                model.setFPickOrgId(new FPickOrgId(ORG_ID));
                model.setFStockDirect("GENERAL");
                model.setFBizType("0");
                model.setFCustId(new FCustId("CUST0067"));
                model.setFOwnerTypeIdHead(OWNER_TYPE_ID);
                model.setFOwnerIdHead(new FOwnerIdHead(ORG_ID));
                model.setFEntity(fEntities);
                models[index++] = model;

                KingErpBillRecord billRecord = KingErpBillRecord.builder().
                        billDate(DateUtils.formatStringToDate(useOrder.getBizDate())).billType(ErpOrderTypeEnum.ERP_ORDER_TYPE_7.getValue().toString())
                        .orderNo(useOrder.getOrderNo()).createTime(new Date()).stationId(Long.valueOf(useOrder.getStoreCode())).isDel(0).build();
                records.add(billRecord);
            }
            OtherOutBatchRequest otherOutBatchRequest = new OtherOutBatchRequest();
            otherOutBatchRequest.setModel(models);
            otherOutBatchRequest.setIsAutoSubmitAndAudit(true);
            Gson requestGson = new Gson();
            String requestJson = requestGson.toJson(otherOutBatchRequest);
            RepoResult repoResult = KingDeeUtils.batchSave(FormId_OtherOrder, requestJson);
            if (repoResult.getResponseStatus().isIsSuccess()) {
                for (KingErpBillRecord record : records) {
                    record.setStatus(1);
                    record.setUpdateTime(new Date());
                    kingErpBillRecordService.save(record);
                }
                return R.ok().put("data", repoResult.getResult());
            } else {
                String msg = KingDeeUtils.toErrorMessageString(repoResult.getResponseStatus().getErrors());
                for (KingErpBillRecord record : records) {
                    record.setStatus(0);
                    record.setResponText(msg);
                    record.setUpdateTime(new Date());
                    kingErpBillRecordService.save(record);
                }
                return R.error(msg);
            }
        }
        return R.ok("未查询到单据数据！");
    }
}
